
package com.gitee.jmash.oidc.client.web.controller;

import java.io.IOException;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.SavedRequest;
import org.apache.shiro.web.util.WebUtils;
import com.gitee.jmash.common.event.SafeEvent;
import com.gitee.jmash.oidc.client.web.models.LoginRedirect;
import jakarta.enterprise.context.RequestScoped;
import jakarta.enterprise.event.Event;
import jakarta.inject.Inject;
import jakarta.mvc.Controller;
import jakarta.mvc.Models;
import jakarta.mvc.MvcContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.core.Context;

/** Login . */
@Path("login")
@Controller
@RequestScoped
public class LoginController {

  @Inject
  private Models models;
  @Inject
  private MvcContext mvc;
  /** Login Redirect @RedirectScoped. */
  @Inject
  private LoginRedirect loginRedirect;
  /** 安全日志. */
  @Inject
  Event<SafeEvent> event;

  /** Login View. */
  @GET
  public String execute(@QueryParam("backurl") String backurl, @Context HttpServletRequest req,
      @Context HttpServletResponse resp) throws IOException {
    if (StringUtils.isNotBlank(backurl)) {
      models.put("backurl", backurl);
    }
    if (StringUtils.isNotBlank(loginRedirect.getBackurl())) {
      models.put("backurl", loginRedirect.getBackurl());
    }

    Subject subject = SecurityUtils.getSubject();
    if (subject.isAuthenticated() || subject.isRemembered()) {
      return loginSuccess(backurl, req, resp);
    }

    return "login.ftl";
  }


  /** Login Success Redirect. */
  public String loginSuccess(String backurl, HttpServletRequest req, HttpServletResponse resp)
      throws IOException {
    SavedRequest savedRequest = WebUtils.getAndClearSavedRequest(req);
    // Redirect backurl.
    if (StringUtils.isNotBlank(backurl)) {
      resp.sendRedirect(backurl);
      return null;
    } else if (savedRequest != null
        && savedRequest.getMethod().equalsIgnoreCase(AccessControlFilter.GET_METHOD)) {
      resp.sendRedirect(savedRequest.getRequestUrl());
      return null;
    } else {
      resp.sendRedirect(mvc.uri("DefaultController#execute").toString());
      return null;
    }
  }

}
